<?php

namespace app\admin\model\deerhome;

use think\Model;
use app\admin\model\deerhome\Xcxmsg;

class SmsLog extends Model
{

    // 表名
    protected $name = 'deerhome_sms_log';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
    
    public function getTypeList()
    {
        return ['1' => "验证码", '2' => "通知短信"];
    }
    public function yzmEncode($code){
        return md5("DeerHome_e2KM7Cd5".$code);
    }
    public function checkYzm($tel,$code){
        $code=$this->yzmEncode($code);
        $sms = $this->where(['tel'=>$tel,'code'=>$code])->find();
        if(!$sms){
            return false;
        }
        //5分钟内有效
        if(time()-strtotime($sms->sendtime)>300){
            return false;
        }
        $sms->is_yz=1;
        $sms->yz_time=\date("Y-m-d H:i:s");
        $sms->save();
        return true;
    }
    public function sendYzm($tel){
        $code=rand(100000,999999);
        $arr=[];
        $arr["code"]=$code;
        $this->send($tel,$arr,'yzm',1);
    }
    public function send($tel,$arr,$tpl,$type=2){
        if(!preg_match("/^1\d{10}$/", $tel)){
            throw new \Exception("手机号码格式错误");
        }
        //检查是否频繁发送，1天内同一手机号验证码最多发送10次
        if($type==1){
            $count=$this->where("status",1)->where("type",1)->where("tel",$tel)->where("sendtime",">",\date("Y-m-d H:i:s",strtotime("-1 day")))->count();
            if($count>=10){
                throw new \Exception("发送频繁，请明天再试");
            }
        }
        
        $add=[];
        $add["tel"]=$tel;
        $add["type"]=$type;
        $add["status"]=1;
        $add["msg"]=$this->getMsgCon($arr,$tpl);
        $add["note"]="发送成功";
        $add["sendtime"]=\date("Y-m-d H:i:s");
        if($type==1){
            $add["msg"]="验证码短信，内容保密";
            $add["code"]=$this->yzmEncode($arr["code"]);
        }
        $errMsg="";
        try{
            \Tools\AliyunSms::send($tel,$arr,$tpl);
        }catch(\Exception $e){
            $add["status"]=2;
            $add["note"]=$e->getMessage();
            $errMsg=$e->getMessage();
        }
        $this->save($add);
        if($errMsg){
            throw new \Exception($errMsg);
        }
    }
    public function getMsgCon($arr,$tpl){
        $msg=Xcxmsg::where("sms_template_code",$tpl)->value("sms_tpl");
        if(!$msg){
            return '短信模板【'.$tpl.'】不存在';
        }
        foreach($arr as $k=>$v){
            $msg=str_replace('${'.$k.'}',$v,$msg);
        }
        return $msg;
    }


}
